<?php

namespace app\api\controller\wanlshop;

use addons\wanlshop\library\WanlPay\WanlPay;
use addons\wanlshop\library\WanlSdk\Common;
use app\admin\controller\wanlshop\Seckill;
use app\admin\model\video\Videovip;
use app\admin\model\wanlshop\Bank;
use app\admin\model\wanlshop\GroupsOrder;
use app\api\model\wanlshop\ShopPayOrder;
use app\api\model\wanlshop\ShopSort;
use app\common\controller\Api;
use app\common\controller\QrCodeService;
use app\common\library\Qpay;
use app\common\library\RussianPay;
use app\common\library\SfdPay;
use app\index\controller\wanlshop\Seckillorder;
use app\index\model\wanlshop\ShopMarginOrder;
use think\Cache;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Request;
use function EasyWeChat\Kernel\Support\get_client_ip;


/**
 * WanlShop支付接口
 */
class Pay extends Api
{
    protected $noNeedLogin = ['shopPayment'];
    protected $noNeedRight = ['*'];

    /**
     * 获取支付信息 ----
     *
     * @ApiSummary  (WanlShop 获取支付信息)
     * @ApiMethod   (POST)
     *
     * @param string $id 订单ID
     */
    public function getPay()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $id = $this->request->post('order_id');
            $id ? $id : ($this->error(__('非法请求')));
            $order_type = $this->request->post('order_type');
            // 1.0.8升级 拼团

            if ($order_type == 'groups') {
                $model_order = model('app\api\model\wanlshop\groups\Order');
            } else if ($order_type == 'seckill') {
                $model_order = model('app\api\model\wanlshop\seckill\Order');
            } else {
                $model_order = model('app\api\model\wanlshop\Order');
                $order_type = 'goods';
            }
            // 判断权限
            $orderState = $model_order
                ->where(['id' => $id, 'user_id' => $this->auth->id])
                ->find();
            $orderState['state'] != 1 ? ($this->error(__('订单异常'))) : '';
            // 获取支付信息 1.1.2升级
            $pay = model('app\api\model\wanlshop\Pay')
                ->where(['order_id' => $id, 'type' => $order_type])
                ->field('id,order_id,order_no,pay_no,price')
                ->find();
            $pay['order_type'] = $order_type;
            // 传递Token
            $pay['token'] = Common::creatToken('orderToken_' . $this->auth->id);
            $this->success('ok', $pay);
        }
        $this->error(__('非法请求'));
    }

    /**
     * 支付订单
     *
     * @ApiSummary  (WanlShop 支付订单)
     * @ApiMethod   (POST)
     *
     * @param string $order_id 订单ID
     * @param string $type 支付类型
     */
    public function payment()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $order_id = $this->request->post('order_id/a');
            $order_id ? $order_id : ($this->error(__('非法请求')));
            $order_type = $this->request->post('order_type');
            $type = $this->request->post('type');
            $method = $this->request->post('method');
            $code = $this->request->post('code');
            $token = $this->request->post('token');
            $password = $this->request->post('password');
            if((int)config('site.is_pay_pwd') == 1){
                if ($method == 'balance' || $method == 'wallet') {
                    if (!$password) {
                        $this->error(__('请输入支付密码'));
                    }
                    $password = $this->auth->getEncryptPassword($password, $this->auth->salt);
                    if ($password !== $this->auth->pay_password) {
                        $this->error(__('支付密码错误'));
                    }
                }
            }
            // 验证Token
            if ($token) {
                if (!Common::checkToken($token, 'orderToken_' . $this->auth->id)) {
                    $this->error(__('页面安全令牌已过期！请重返此页'));
                }
            } else {
                $this->error(__('非法提交，未传入Token'));
            }
            $user_id = $this->auth->id;
            $type ? $type : ($this->error(__('未选择支付类型')));

            // 1.0.8升级 拼团
            if ($order_type == 'groups') {
                $model_order = model('app\api\model\wanlshop\groups\Order');
                $model_order_goods = model('app\api\model\wanlshop\groups\OrderGoods');
                $model_goods = model('app\api\model\wanlshop\groups\Goods');
                $model_goods_sku = model('app\api\model\wanlshop\groups\GoodsSku');
            } else if ($order_type == 'seckill') {
                $model_order = model('app\api\model\wanlshop\seckill\Order');
                $model_order_goods = model('app\api\model\wanlshop\seckill\OrderGoods');
                $model_goods = model('app\api\model\wanlshop\seckill\Goods');
                $model_goods_sku = model('app\api\model\wanlshop\seckill\GoodsSku');
            } else {
                $model_order = model('app\api\model\wanlshop\Order');
                $model_order_goods = model('app\api\model\wanlshop\OrderGoods');
                $model_goods = model('app\api\model\wanlshop\Goods');
                $model_goods_sku = model('app\api\model\wanlshop\GoodsSku');
                $order_type = 'goods';
            }

            // 判断权限
            $order = $model_order
                ->where('id', 'in', $order_id)
                ->where('user_id', $user_id)
                ->select();
            if (!$order) {
                $this->error(__('没有找到任何要支付的订单'));
            }
            foreach ($order as $item) {
                if ($item['state'] != 1) {
                    $this->error(__('订单已支付，或网络繁忙'));
                }
                // 1.0.5升级 修复付款减库存
                foreach ($model_order_goods->where('order_id', $item['id'])->select() as $data) {
                    // 1.1.10升级  判断前端商品数量0
                    if ($data['number'] <= 0) {
                        $this->error("操作异常");
                    }
                    $redis = Common::redis();
                    // 获取sku
                    $sku = $model_goods_sku->get($data['goods_sku_id']);
                    // 1.1.2升级
                    $sku_key = $order_type . '_' . $sku['goods_id'] . '_' . $sku['id'];
                    // 查询商品
                    $goods = $model_goods
                        ->where(['id' => $data['goods_id'], 'stock' => 'payment'])
                        ->find();
                    // 库存计算方式:porder=下单减库存,payment=付款减库存 1.0.8升级
                    if ($goods) {
                        // 1.1.2升级
                        if ($data['number'] > $redis->llen("{$sku_key}")) {
                            $this->error("系统繁忙，请稍后抢购！");
                        } else {
                            for ($i = 0; $i < $data['number']; $i++) {
                                $redis->rpop("{$sku_key}");
                            }
                            $sku->setDec('stock', $data['number']); // 1.0.3升级
                        }
                    }
                }
            }
            // 调用支付
            $wanlPay = new WanlPay($type, $method, $code);
            $data = $wanlPay->pay($order_id, $order_type);
            if ($data['code'] == 200) {
                $this->success('ok', $data['data']);
            } else {
                $this->error($data['msg']);
            }
        }
        $this->error(__('非正常请求'));
    }


    /**
     * 获取银行卡
     */
    public function getBankCardInfo(){
        $this->success('ok',['bankCardNumber'=>config('site.admin_bank_number'),'transfer_bank'=>config('site.transfer_bank')]);
    }

    /**
     * 上传订单截图
     */

    public function bankCardAdd(){
        $data = input('post.');
        if(empty($data['pay_no']) || empty($data['images']) || empty($data['bankCardNumber'])){
            $this->error(__('缺少参数'));
        }
        $payModel = new \app\api\model\wanlshop\Pay();
        $payInfo = $payModel->where(['pay_no'=>$data['pay_no']])->find();
        if(!$payInfo){
            $this->error(__('订单不存在'));
        }
        if($payInfo->pay_type != 7){
            $payInfo->pay_type = 6;
        }
        $payInfo->bank_card_number = $data['bankCardNumber'];
        if(empty($data['remarks'])){
            $payInfo->remarks = $data['remarks'];
        }
        $payInfo->images = implode(',',$data['images']);
        $payInfo->save();
        $this->success('ok');
    }



    /**
     * 用户充值
     */
    public function recharge()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $money = $this->request->post('money');
            $type = $this->request->post('type');
            $method = $this->request->post('method');
            $code = $this->request->post('code');
            $user_id = $this->auth->id;
            $type ? $type : ($this->error(__('未选择支付类型')));
            $money ? $money : ($this->error(__('为输入充值金额')));
            // 调用支付
            $wanlPay = new WanlPay($type, $method, $code);
            $data = $wanlPay->recharge($money);
            if ($data['code'] == 200) {
                $this->success($data['msg'], $data['data']);
            } else {
                $this->error($data['msg']);
            }
        }
        $this->error(__('非正常请求'));
    }


    /**
     * 用户线下付款
     */
    public function shopPayment()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $money = $this->request->post('money');
            $payType = $this->request->post('pay_type', '');
            $inviteCode = $this->request->post('invite_code', 0);
            if (!$inviteCode) {
                $this->error(__('缺少参数'));
            }
            if ($money <= 0) {
                $this->error(__('请输入正确的金额'));
            }
            if (!$payType || !in_array($payType, ['wallet', 'balance', 'bank','qpay','bank_image','wechat'])) {
                $this->error(__('pay_type参数错误'));
            }
            $isIpCn =  isIpCn(get_client_ip());
            if ($isIpCn) {
//                $this->error(__('当前换成不支持付款'));
            }
            $state = 1;
            $actualPayment = $money;
            if ($payType == 'balance') {
                $state = 2;
                if ($this->auth->money < $money) {
                    $this->error(__('Боломжит үлдэгдэл хангалтгүй'));
                }
                $userId = $this->auth->id;
            } else if ($payType == 'wallet') {
                $state = 2;
                if ($this->auth->wallet < $money) {
                    $this->error(__('Боломжит үлдэгдэл хангалтгүй'));
                }
                $userId = $this->auth->id;
            }else{
                $actualPayment = '0';
                $userId = $this->auth->id??0;
            }
            $userInfo = \app\common\model\User::where(['invite_code'=>$inviteCode])->find();
            if (!$userInfo) {
                $this->error(__('Дэлгүүр байхгүй'));
            }
            $orderModel = new ShopPayOrder();
            $payModel = model('app\api\model\wanlshop\Pay');
            $webUrl  = '';
//            dump($orderModel->getPayTypeList()[$payType]);exit();
            $receiveId = $userInfo['id'];
            $pay_no = '';
            Db::startTrans();
            try {
                $fwf = config('site.shop_xianxia_fwf') / 100;
                //所扣的服务费
                $adminFwf = $money * $fwf;
                //创建线下订单
                $shopMoney = round($money - $adminFwf, 2);
                $orderModel->user_id = $userId;
                $orderModel->pay_type = $payType;
                $orderModel->receive_id = $userInfo['id'];
                $orderModel->order_no = $userId >0 ?$userId:$userInfo['id'];
                $orderModel->total_amount = $money;
                $orderModel->fwf = $adminFwf;
                $orderModel->actual_payment = $actualPayment;//实付金额
                $orderModel->paymenttime = time();
                $orderModel->state = $state;
                $orderModel->save();
                if ($payType != 'bank' && $payType != 'qpay') {
                    //同步生成支付流水表
                    $payModel->pay_no = $orderModel->order_no;
                    $payModel->user_id = $orderModel->user_id;
                    $payModel->order_no = $orderModel->order_no;
                    $payModel->receive_id = $receiveId;
                    $payModel->order_id = $orderModel->id;
                    $payModel->type = 'shop_pay_order';
                    $payModel->number = 1;
                    $payModel->price = $money;
                    $payModel->order_price = $money;
                    $payModel->actual_payment = $money;
                    $payModel->total_amount = $money;
                    if($payType != 'bank_image' && $payType != 'wechat'){
                        $payModel->pay_state = 2;
                        $payModel->pay_type = $orderModel->pay_type=='balance'?1:4;
                        if($payType == 'balance'){
                            controller('addons\wanlshop\library\WanlPay\WanlPay')->money(-$money, $this->auth->id, 'Офлайн төлбөр', 'shop_pay_order', $orderModel->order_no);
                        }else{
                            controller('addons\wanlshop\library\WanlPay\WanlPay')->wallet(-$money, $this->auth->id, 'Офлайн төлбөр', 'shop_pay_order', $orderModel->order_no);
                        }
                        controller('addons\wanlshop\library\WanlPay\WanlPay')->money($shopMoney, $receiveId, 'Офлайн төлбөрийн код цуглуулах', 'shop_pay_order', $orderModel->order_no);
                        commission($orderModel);
                    }else{
                        $payModel->pay_type = 6;
                    }
                    $payModel->save();
                    $pay_no = $payModel->pay_no;
                }else if($payType == 'bank'){
                    $ru = new RussianPay();
                    $params['order_number'] = $orderModel->order_no;
                    $params['body'] = 'Төлбөрөө төл';
                    $params['amount'] = $money;
                    $res = $ru->orderPay($params);
                    if(!$res['web_url']){
                        $this->error($res['msg']);
                    }
                    $orderModel->out_trade_no = $res['out_trade_no'];
                    $orderModel->save();
                    $webUrl = $res['web_url'];
                }else if($payType == 'qpay'){
                    $qpay = new Qpay();
                    $params = [
                        'invoice_code' =>'HAPPYGO_INVOICE',
                        'sender_invoice_no' => $orderModel->order_no,
                        'invoice_receiver_code' => 'terminal',
                        'invoice_description' => 'Төлбөрөө төл',
                        'sender_branch_code' => 'SALBAR1',
                        'amount' => $money,
                        'callback_url' => config('site.qpay_callback_url').'/type/buy',
                    ];
                    $res =$qpay->invoice($params);
                    if($res['status'] != 200){
                        $this->error(__('Боломжит үлдэгдэл хангалтгүй'));
                    }
                    $orderModel->out_trade_no = $res['body']['invoice_id'];
                    $orderModel->save();
                    $webUrl = $res['body']['qPay_shortUrl'];
                }
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('Төлбөр амжилттай',['web_url'=>$webUrl,'pay_no'=>$pay_no]);
        }
        $this->error(__('非正常请求'));
    }



    /**
     * H5保证金缴纳
     */

    public function generateH5Payment(){
        $money = input('money',0);
        if($money <= 0){
            $this->error(__('金额错误'));
        }
        $payType = $this->request->post('pay_type', '');
        if (!$payType || !in_array($payType, ['wallet', 'balance', 'bank','qpay','bank_image','wechat'])) {
            $this->error(__('pay_type参数错误'));
        }
        $where['user_id'] = $this->auth->id;
        $where['verify'] = 3;
        $shopInfo = \app\api\model\wanlshop\Shop::where($where)->find();
        if(!$shopInfo){
            $this->error(__('商户不存在'));
        }
        //余额支付
        if ($payType == 'balance' && $this->auth->money < $money) {
            $this->error(__('余额不足'));
        } else if ($payType == 'wallet' && $this->auth->wallet < $money) {
            $this->error(__('钱包不足'));
        }
        $orderModel = new ShopMarginOrder();
        $orderModel->user_id = $this->auth->id;
        $orderModel->shop_id = $shopInfo->id;
        $orderModel->arrival_id = $shopInfo->arrival_id;
        $orderModel->order_no = $shopInfo->id;
        $orderModel->money  = $money;
        $subject = $shopInfo->shopname.'缴纳'.$money.'元保证金';
        $orderModel->remark = $subject;
        $webUrl = '';
        $order_no = $orderModel->order_no;
        if ($payType == 'balance' || $payType == 'wallet' || $payType == 'wechat') {
            if($payType == 'wechat'){
                $wechatMoney = input('wechat_money');
                $orderModel->save();
                $wanlPay = new WanlPay('wechat', 'mp');
                $data = $wanlPay->shopPaymentPay($orderModel,$wechatMoney);
                if ($data['code'] == 200) {
                    $this->success('ok', $data['data']);
                } else {
                    $this->error($data['msg']);
                }
            }else{
                if($payType == 'balance'){
                    controller('addons\wanlshop\library\WanlPay\WanlPay')->money(-$money, $this->auth->id, 'Офлайн төлбөр', 'shop_pay_order', $orderModel->order_no);
                }else{
                    controller('addons\wanlshop\library\WanlPay\WanlPay')->wallet(-$money, $this->auth->id, 'Офлайн төлбөр', 'shop_pay_order', $orderModel->order_no);
                }
                $orderModel->actual_payment = $money;
                $orderModel->status = 1;
            }
        }else if($payType == 'bank'){
            $ru = new RussianPay();
            $params['order_number'] = $orderModel->order_no;
            $params['body'] = 'Төлбөрөө төл';
            $params['amount'] = $money;
            $res = $ru->orderPay($params);
            if(!$res['web_url']){
                $this->error($res['msg']);
            }
            $orderModel->out_trade_no = $res['out_trade_no'];
            $webUrl = $res['web_url'];
        }else if($payType == 'qpay'){
            $qpay = new Qpay();
            $params = [
                'invoice_code' =>'HAPPYGO_INVOICE',
                'sender_invoice_no' => $orderModel->order_no,
                'invoice_receiver_code' => 'terminal',
                'invoice_description' => 'Төлбөрөө төл',
                'sender_branch_code' => 'SALBAR1',
                'amount' => $money,
                'callback_url' => config('site.qpay_callback_url').'/type/buy',
            ];
            $res =$qpay->invoice($params);

            if($res['status'] != 200){
                $this->error(__('Боломжит үлдэгдэл хангалтгүй'));
            }
            $orderModel->out_trade_no = $res['body']['invoice_id'];
            $webUrl = $res['body']['qPay_shortUrl'];
        }
        $orderModel->save();
        if($payType == 'bank_image'){
            $payModel = model('app\api\model\wanlshop\Pay');
            //同步生成支付流水表
            $payModel->pay_no = $order_no;
            $payModel->user_id = $this->auth->id;
            $payModel->order_no = $order_no;
            $payModel->order_id = $orderModel->id;
            $payModel->type = 'baozhengjin';
            $payModel->number = 1;
            $payModel->price = $money;
            $payModel->order_price = $money;
            $payModel->actual_payment = $money;
            $payModel->total_amount = $money;
            $payModel->pay_type = '7';
            $payModel->save();
            $order_no = $payModel->pay_no;
        }
        $this->success('ok',['web_url'=>$webUrl,'order_no'=>$order_no]);
    }

    /**
     * 商户获取线下二维码
     * @return void
     */
    public function qrcode()
    {

//        $shopId = \app\admin\model\wanlshop\Shop::where(['user_id' => $this->auth->id])->value('id');
        $url = 'https://happygomall.com/#/pages/shop/payment?invite_code=' . $this->auth->invite_code;
        $code = shengcode($url, $this->auth->id.'-'.$this->auth->invite_code, 'shopQrcode');
        $this->success('ok', ['path' =>'https://www.happygomall.com'.trim($code, '.')]);
    }


    /**
     * 用户提现账户
     */
    public function getPayAccount()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $row = model('app\api\model\wanlshop\PayAccount')
                ->where(['user_id' => $this->auth->id])
                ->order('createtime desc')
                ->select();
            $this->success('ok', $row);
        }
        $this->error(__('非正常请求'));
    }

    /**
     * 新增提现账户
     */
    public function addPayAccount()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $post =input('post.');
            $post['user_id'] = $this->auth->id;
            if($post['bankCode'] == 'HEZUO'){
                $post['is_hezuo'] = 1;
            }
            $row = model('app\api\model\wanlshop\PayAccount')->allowField(true)->save($post);
            if ($row) {
                $this->success('ok', $row);
            } else {
                $this->error(__('新增失败'));
            }
        }
        $this->error(__('非正常请求'));
    }

    /**
     * 删除提现账户
     */
    public function delPayAccount($ids = '')
    {
        $row = model('app\api\model\wanlshop\PayAccount')
            ->where('id', 'in', $ids)
            ->where(['user_id' => $this->auth->id])
            ->delete();
        if ($row) {
            $this->success('ok', $row);
        } else {
            $this->error(__('删除失败'));
        }
    }

    /**
     * 初始化提现
     */
    public function initialWithdraw()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $config = get_addon_config('wanlshop');
            $bank = model('app\api\model\wanlshop\PayAccount')
                ->where(['user_id' => $this->auth->id])
                ->order('createtime desc')
                ->find();
            $isIpCn = isIpCn(get_client_ip());
//            $isIpCn = false;
            if ($isIpCn) {
                $withdrawDesc = $config['withdraw']['withdraw_content'];
            } else {
                $withdrawDesc = $config['withdraw']['russian_withdraw_content'];
            }
           $currency = input('currency');
            $userMoney = $this->auth->money;
            if($currency == 'cny'){
                $userMoney = $userMoney / $config['config']['mg_rate'];
                $config['withdraw']['russian_servicefee'] = 0;
            }
            if($userMoney <= $config['withdraw']['russian_servicefee']){
                $userMoney = 0;
            }else{
                $userMoney = round($userMoney - $config['withdraw']['russian_servicefee'],2);
            }
            $this->success('ok', [
                'money' => $userMoney,
                'wallet' => $this->auth->wallet,
                'servicefee' => $config['withdraw']['servicefee'],
                'russian_servicefee' => $config['withdraw']['russian_servicefee'],
                'bank' => $bank,
                'withdrawDesc' => $withdrawDesc,
                'isIpCn' => $isIpCn,
                'russian_wallet_content' => $config['withdraw']['russian_wallet_content']??'',
            ]);
        }
        $this->error(__('非正常请求'));
    }

    /**
     * 获取银行列表
     * @return void
     */
    public function bankList(){
        $bankModel = new Bank();
        $arr = $bankModel->order('weigh desc')->select();
        $this->success('ok',['bankList'=>$arr]);
    }

    /**
     * 用户提现
     */
    public function withdraw()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            // 金额
            $money = $this->request->post('money');
            $isWallet =  $this->request->post('is_wallet',0);
            $request =  Request::instance();
            // 账户
            $account_id = $this->request->post('account_id');
            if ($money <= 0) {
                $this->error('提现金额不正确');
            }
            $currency = input('currency');
            $config = get_addon_config('wanlshop');
            $min_wallet     = $cny_min_wallet = config('site.min_wallet');
            $min_user_money = $cny_user_money = config('site.min_user_money');
            if($currency == 'cny'){
                $money = $money * $config['config']['mg_rate'];
                $cny_min_wallet = $min_wallet / $config['config']['mg_rate'];
                $cny_user_money = $min_user_money / $config['config']['mg_rate'];
            }
            if ($money > $this->auth->money) {
                $this->error('提现金额超出可提现额度');
            }
            if (!$account_id) {
                $this->error("提现账户不能为空");
            }
            // 查询提现账户
            $account = \app\api\model\wanlshop\PayAccount::where(['id' => $account_id, 'user_id' => $this->auth->id])->find();
            if (!$account) {
                $this->error("提现账户不存在");
            }
            if($request->langset() == 'zh-cn'){

                if ($config['withdraw']['state'] == 'N') {
                    $this->error("系统该关闭提现功能，请联系平台客服");
                }
                if (isset($config['withdraw']['minmoney']) && $money < $config['withdraw']['minmoney']) {
                    $this->error('提现金额不能低于' . $config['withdraw']['minmoney'] . '元');
                }
                if ($config['withdraw']['monthlimit']) {
                    $count = \app\api\model\wanlshop\Withdraw::where('user_id', $this->auth->id)->whereTime('createtime', 'month')->count();
                    if ($count >= $config['withdraw']['monthlimit']) {
                        $this->error("已达到本月最大可提现次数");
                    }
                }
                // 计算提现手续费
                if ($config['withdraw']['servicefee'] && $config['withdraw']['servicefee'] > 0) {
                    $servicefee = number_format($money * $config['withdraw']['servicefee'] / 1000, 2);
                    $handingmoney = $money - number_format($money * $config['withdraw']['servicefee'] / 1000, 2);
                } else {
                    $servicefee = 0;
                    $handingmoney = $money;
                }
            }else{
                $baifenbi = true;
                if($isWallet == 1){
                    if($money < $min_wallet){
                        $this->error("最小提前金额".$cny_min_wallet);
                    }
                    if($money > $this->auth->wallet){
                        $this->error("超出钱包数量");
                    }
                    if($account['is_hezuo'] == 1){
                        $servicefee = config('site.cooperation_wallet');//钱包合作方提现手续费
                    }else{
                        $servicefee = config('site.no_cooperation_wallet');//钱包非合作方提现手续费
                    }
                }else{
                    if($money < $min_user_money){
                        $this->error("最小提前金额".$cny_user_money);
                    }
                    if($money > $this->auth->money){
                        $this->error("余额数量");
                    }
                    if($account['is_hezuo'] == 1){
                        $baifenbi = false;
                        $servicefee = config('site.cooperation_money');//余额合作方提现手续费
                    }else{
                        $servicefee = config('site.no_cooperation_money');//余额非合作方提现手续费
                    }
                }
                //人民币类型，不扣手续费
                if($currency == 'cny'){
                    $servicefee = 0;
                }
                if ($servicefee > 0) {
                    if($baifenbi){
                        $servicefee  =  round($money * $servicefee / 1000,2);
                    }
                    $handingmoney = $money - $servicefee;
                } else {
                    $servicefee = 0;
                    $handingmoney = $money;
                }
            }

            $config = get_addon_config('wanlshop');
            $rmb_money = $handingmoney;
            if($config['config']['mg_rate'] > 0){
                $rmb_money = round($rmb_money / $config['config']['mg_rate'],2);
            }
            Db::startTrans();
            try {
                $data = [
                    'user_id' => $this->auth->id,
                    'money' => $handingmoney,
                    'rmb_money' => $rmb_money,//人民币
                    'handingfee' => $servicefee, // 手续费
                    'type' => $account['bankCode'],
                    'is_wallet' => $isWallet,
                    'account' => $account['cardCode'],
                    'currency' => $currency,
                    'orderid' => date("Ymdhis") . sprintf("%08d", $this->auth->id) . mt_rand(1000, 9999)
                ];
                $withdraw = \app\api\model\wanlshop\Withdraw::create($data);
                $pay = new WanlPay;
                if($isWallet == 1){
                    $pay->wallet(-$money, $this->auth->id, '申请提现', 'withdraw', $withdraw['id']);
                }else{
                    $pay->money(-$money, $this->auth->id, '申请提现', 'withdraw', $withdraw['id']);
                }

                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('提现申请成功！请等待后台审核', $this->auth->money);
        }
        $this->error(__('非正常请求'));
    }

    /**
     * 获取提现日志
     */
    public function withdrawLog()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $isWallet = input('is_wallet',0);
        if ($this->request->isPost()) {
            $list = model('app\api\model\wanlshop\Withdraw')
                ->where('user_id', $this->auth->id)
                ->where('is_wallet', $isWallet)
                ->order('createtime desc')
                ->paginate();
            $this->success('ok', $list);
        }
        $this->error(__('非法请求'));
    }

    /**
     * 获取支付日志
     */
    public function moneyLog()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $list = model('app\common\model\MoneyLog')
                ->where('user_id', $this->auth->id)
                ->order('createtime desc')
                ->paginate();
            $this->success('ok', $list);
        }
        $this->error(__('非法请求'));
    }

    /**
     * 钱包日志
     * @return void
     * @throws DbException
     */
    public function walletLog()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $list = model('app\common\model\WalletLog')
                ->where('user_id', $this->auth->id)
                ->order('createtime desc')
                ->paginate();
            $this->success('ok', $list);
        }
        $this->error(__('非法请求'));
    }

    /**
     * 获取Go币日志
     */
    public function goMoneyLog()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $list = model('app\common\model\GoMoneyLog')
                ->where('user_id', $this->auth->id)
                ->order('createtime desc')
                ->paginate();
            $this->success('ok', $list);
        }
        $this->error(__('非法请求'));
    }

    /**
     * 获取支付详情
     */
    public function details($id = null, $type = null)
    {
        if ($type == 'pay') {
            $field = 'id,shop_id,createtime,paymenttime';
            $order = model('app\api\model\wanlshop\Order')
                ->where('order_no', 'in', $id)
                ->where('user_id', $this->auth->id)
                ->field($field)
                ->select();
            //1.0.5升级 临时修改,后续升级版本重构
            if (!$order) {
                $shop = model('app\api\model\wanlshop\Shop')->get(['user_id' => $this->auth->id]);
                $order = model('app\api\model\wanlshop\Order')
                    ->where('order_no', 'in', $id)
                    ->where('shop_id', $shop['id'])
                    ->field($field)
                    ->select();
                if (!$order) $this->error(__('订单异常'));
            }
            foreach ($order as $vo) {
                // 1.1.2升级
                $vo['pay'] = model('app\api\model\wanlshop\Pay')
                    ->where(['order_id' => $vo['id'], 'type' => 'goods'])
                    ->field('price,pay_no,order_no,order_price,trade_no,actual_payment,freight_price,discount_price,total_amount')
                    ->find();
                $vo->shop->visible(['shopname']);
                $vo->goods = model('app\api\model\wanlshop\OrderGoods')
                    ->where(['order_id' => $vo['id']])
                    ->field('id,title,difference,image,price,number')
                    ->select();
            }
            $this->success('ok', $order);
        } else if ($type == 'groups') {
            $field = 'id,shop_id,createtime,paymenttime';
            $order = model('app\api\model\wanlshop\groups\Order')
                ->where('order_no', 'in', $id)
                ->where('user_id', $this->auth->id)
                ->field($field)
                ->select();
            //1.0.5升级 临时修改,后续升级版本重构
            if (!$order) {
                $shop = model('app\api\model\wanlshop\Shop')->get(['user_id' => $this->auth->id]);
                $order = model('app\api\model\wanlshop\groups\Order')
                    ->where('order_no', 'in', $id)
                    ->where('shop_id', $shop['id'])
                    ->field($field)
                    ->select();
                if (!$order) $this->error(__('订单异常'));
            }
            foreach ($order as $vo) {
                // 1.1.2升级
                $vo['pay'] = model('app\api\model\wanlshop\Pay')
                    ->where(['order_id' => $vo['id'], 'type' => 'groups'])
                    ->field('price,pay_no,order_no,order_price,trade_no,actual_payment,freight_price,discount_price,total_amount')
                    ->find();
                $vo->shop->visible(['shopname']);
                $vo->goods = model('app\api\model\wanlshop\groups\OrderGoods')
                    ->where(['order_id' => $vo['id']])
                    ->field('id,title,difference,image,price,number')
                    ->select();
            }
            $this->success('ok', $order);
        } else if ($type == 'recharge' || $type == 'withdraw') { // 用户充值
            if ($type == 'recharge') {
                $model = model('app\api\model\wanlshop\RechargeOrder');
                $field = 'id,paytype,orderid,memo';
            } else {
                $model = model('app\api\model\wanlshop\Withdraw');
                $field = 'id,money,handingfee,status,type,account,orderid,memo,transfertime';
            }
            $row = $model
                ->where(['id' => $id, 'user_id' => $this->auth->id])
                ->field($field)
                ->find();
            $this->success('ok', $row);
        } else if ($type == 'refund') {
            $order = model('app\api\model\wanlshop\Order')
                ->where('order_no', $id)
                ->where('user_id', $this->auth->id)
                ->field('id,shop_id,order_no,createtime,paymenttime')
                ->find();
            if (!$order) {
                $this->success('ok');
            }
            $order->shop->visible(['shopname']);
            $order['refund'] = model('app\api\model\wanlshop\Refund')
                ->where(['order_id' => $order['id'], 'user_id' => $this->auth->id])
                ->field('id,price,type,reason,createtime,completetime')
                ->find();
            $this->success('ok', $order);
        } else { // 系统
            $this->success('ok');
        }
    }

    /**
     * 获取余额
     */
    public function getBalance()
    {
        $type = input('type', 1);
        if ($type == 1) {
            $this->success('ok', $this->auth->money);
        } else if($type == 3) {
            $this->success('ok', $this->auth->wallet);
        }else{
            $this->success('ok', $this->auth->go_money);
        }
    }


    public function videoVip(){
        $data = Videovip::where(['status'=>1])->select();
        $this->success('ok',$data);
    }
}